const express = require('express')
const router = express.Router()
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const db = require('../db')
const consts = require('../../consts/Consts')
const os = require('os')

// /home/cocos/workspace/wb/vue_chuanbo/server/upload/1841edc0353aa8360530a54199cd4044'
// console.log(__dirname)
const upload = multer({ dest: path.join(__dirname, '../../upload') })
router.use(upload.any())
router.post('/', function(req, res) {
  // console.log('upload body:%o', req.body)
  // console.log('upload files:%o', req.files)
  const responseAfterUpdateTask = function(paths) {
    console.log('upload updateTask body:%o', req.body)
    db.TaskDb.updateTask(req.body, paths, cb => {
      console.log('updateTask cb:%o', cb)
      if (cb == null) {
        res.send({
          code: consts.RES_OK,
          result: {}
        })
      } else {
        res.send({
          code: consts.RES_UPLOAD_ERROR,
          result: {}
        })
      }
    })
  }
  if (req.files.length > 0) {
    let PromiseArr = Array(req.files.length)
    for (let i = 0; i < req.files.length; i++) {
      PromiseArr[i] = new Promise((resolve, reject) => {
        const originalPath = req.files[i].path
        const extname = path.extname(req.files[i].originalname)
        // const newPath = originalPath.replace('/upload/', '/upload/' + req.body.Code + '/') + extname
        const newPath = originalPath + extname
        const newFileName = req.files[i].filename + extname
        console.log('originalPath:%s , newPath:%s', originalPath, newPath)
        // 异步
        fs.rename(originalPath, newPath, function(err) {
          console.log('rename')
          if (err) {
            reject(err)
          } else {
            const url = req.protocol + '://' + req.host + ':3658' + '/' + newFileName
            console.log('url:%s', url)
            resolve(url)
          }
        })
      })
    }
    Promise.all(PromiseArr).then(array => {
      console.log('cyw:%o', array)
      responseAfterUpdateTask(array.join(','))
    })
  } else {
    responseAfterUpdateTask(null)
  }
})

// 本机ip
function getIP() {
  const interfaces = os.networkInterfaces()
  for (const devName in interfaces) {
    const iface = interfaces[devName]
    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i]
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address
      }
    }
  }
}

module.exports = router
